import { SHARE_CHANNEL } from "../const/MSG";
import { httpUtil } from "../framework/modules/httpUtil";
import Common from "../utils/Common";
import { Debug } from "../utils/Debug";
import MathUtils from "../utils/MathUtils";
import PlatformModule from "./PlatformModule";

export default class TTModule extends PlatformModule {

    public platformName: string = "tt";
    public recordRes: any = null;
    public recordCb: any = null;
    public recordNumber: number = 0;
    public moreGameCb: (res: number) => void = null;
    constructor() {
        super();
        this._regisiterWXCallback();
        this._registerTTCallback();
        this.initRecord();


    }
    private _registerTTCallback() {
        if (!window[this.platformName]) return;
        // 监听弹窗关闭
        if (window[this.platformName].onMoreGamesModalClose)
            window[this.platformName].onMoreGamesModalClose((res) => {
                Debug.log("modal closed", res);
                if (this.moreGameCb)
                    this.moreGameCb(0);
            });
        // 监听小游戏跳转
        if (window[this.platformName].onNavigateToMiniGameBox) {
            window[this.platformName].onNavigateToMiniGameBox((res) => {
                Debug.log('onNavigateToMiniGameBox', res);
            })
        }
        else if (window[this.platformName].onNavigateToMiniProgram)
            window[this.platformName].onNavigateToMiniProgram((res) => {
                Debug.log('onNavigateToMiniProgram', res);
            })
    }
    public initRecord() {
        if (!window[this.platformName]) return;
        if (!window[this.platformName].getGameRecorderManager) return;
        // if (!this.isDouyin()) return;
        this.recordObj = window[this.platformName].getGameRecorderManager();
    }
    /**
    * 裁剪视频
    * @param timeRange 默认[2,2] 裁剪视频时保留的前后时长
    * @param callback 剪切完成时回调
    */
    public clipRecord(timeRange: Array<number> = [2, 2], callback: (res: any) => void) {
        if (!this.recordObj) return;
        this.recordNumber++;
        Debug.log('clipRecord', this.recordNumber)
        this.recordObj.recordClip({
            timeRange: timeRange,
            success: (r) => {
                Debug.log('clipRecord 成功 ', r)
                if (Common.isFunction(callback))
                    callback(r)
            }
        })
    }
    /**
     * 开始录屏
     * @param duration 录屏时长
     * @param callback 如果不是抖音回调参数=false
     */
    public startRecord(duration = 300, callback = null) {
        Debug.log('record startRecord');
        if (!this.recordObj) {
            if (callback)
                callback(false);
            return;
        }

        this.recordNumber = 0;
        this.recordCb = null;
        this.recordRes = null;

        this.recordObj.onStart(res => {
            Debug.log('record onStart');
            if (callback)
                callback(res);
        });

        let recordRes = this.recordRes
        this.recordObj.onStop(res => {
            Debug.log('on stop ', res)
            if (this.recordNumber >= 1) {
                this.recordObj.clipVideo({
                    path: res.videoPath,
                    success: (r) => {
                        Debug.log('record clip succes:', r);
                        this.recordRes = r;
                        Debug.log('record clip recordRes :', this.recordRes);
                        if (this.recordCb)
                            this.recordCb(r);
                    },
                    fail: () => {
                        Debug.log('record clip fail:', res);
                        this.recordRes = res;
                        if (this.recordCb)
                            this.recordCb(res);
                    }
                })
            } else {
                this.recordRes = res;
                if (this.recordCb)
                    this.recordCb(res);
            }
        });
        this.recordObj.start({
            duration
        });
    }

    /**
     * 停止录屏
     * @param callback 如果不是抖音回调参数=false，如果录制成功，回调参数中录屏地址=res.videoPath
     */
    public stopRecord(callback = null) {
        Debug.log(' stop Record  callback  ', !!callback);
        if (!this.recordObj) {
            if (callback)
                callback(false);
            return;
        }
        Debug.log('record stop recordRes ', this.recordRes)
        if (this.recordRes) {
            if (Common.isFunction(callback))
                callback(this.recordRes);
        } else {
            this.recordCb = callback;
            this.recordObj.stop();
            Debug.log('record stop  ', this.recordRes)
        }
    }

    public pauseRecord() {
        if (this.recordObj)
            this.recordObj.pause()
    }
    public resumeRecord() {
        if (this.recordObj)
            this.recordObj.resume()
    }


    /**
      * 分享
      * @param query 分享参数 { channel:moosnow.SHARE_CHANNEL.LINK }  
      * SHARE_CHANNEL.LINK, SHARE_CHANNEL.ARTICLE, SHARE_CHANNEL.TOKEN, SHARE_CHANNEL.VIDEO 可选 仅字节跳动有效
      * @param callback 分享成功回调参数 = true, 分享失败回调参数 = false,
      * @param shortCall 时间过短时回调 ,err 是具体错误信息，目前只在头条分享录屏时用到
      */
    public share(query: SHARE_CHANNEL, callback?: (shared: boolean) => void, shortCall?: (err: any) => void) {
        this.currentShareCallback = callback;
        this.currentShortCall = shortCall;
        Debug.log('是否有回调：', shortCall)
        let shareInfo = this.buildShareInfo2(query);
        Debug.log('shareInfo:', shareInfo);
        if (!window[this.platformName]) {
            this.currentShareCallback(true)
            return
        };;
        if (!window[this.platformName].shareAppMessage) {
            this.currentShareCallback(true)
            return
        };
        window[this.platformName].shareAppMessage(shareInfo);
    }

    private shareVideoId: number;
    public buildShareInfo2(channel: SHARE_CHANNEL) {
        let title = "", imageUrl = ""
        if (this.shareInfoArr.length > 0) {
            let item = this.shareInfoArr[MathUtils.randomNumBoth(0, this.shareInfoArr.length - 1)];
            title = item.title;
            imageUrl = item.img;
        }
        if ([SHARE_CHANNEL.LINK, SHARE_CHANNEL.ARTICLE, SHARE_CHANNEL.TOKEN, SHARE_CHANNEL.VIDEO].indexOf(channel) != -1) {
            channel = channel;
        }
        // Debug.log('this. recordRes ', this.recordRes)
        //"https://liteplay-1253992229.cos.ap-guangzhou.myqcloud.com/1.mp4";//
        let videoPath = (this.recordRes && this.recordRes.videoPath) ? this.recordRes.videoPath : "";
        Debug.log('video path ', videoPath)
        return {
            channel: channel,
            title: title,
            imageUrl: imageUrl,
            query: "",// httpUtil._object2Query(query),
            extra: {
                videoPath: videoPath,
                videoTopics: [title],
                withVideoId: true,
            },
            success: (res) => {
                Debug.log('share video success :', res)
                this.shareVideoId = res.videoId
                if (this.currentShareCallback)
                    this.currentShareCallback(true);
            },
            fail: (e) => {
                Debug.log('share video fail ', e)
                Debug.log('index of : ', e.errMsg.indexOf('short'))
                if (e && e.errMsg && e.errMsg.indexOf('short') != -1 && this.currentShortCall) {
                    Debug.log('时间太短 执行回调')
                    this.currentShortCall(e);
                    return;
                }
                if (this.currentShareCallback)
                    this.currentShareCallback(false);
            }
        }
    }
}
